﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Remind.Model;
using Remind.BLL;
using Aptech.UI;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Media;
using Microsoft.Win32;
using Remind.View.Properties;


namespace Remind.View
{
    public partial class frmMain : Form
    {
        //分组业务层对象
        private readonly GroupBLL gBLL = new GroupBLL();
        //联系人业务曾对象
        private readonly ContactsBLL cBLL = new ContactsBLL();
        //当前使用用户
        UserInfo user = null;
        //头像路径
        private string path = Application.StartupPath + "\\face";

        //声音播放文件路径
        private string soundpath = Application.StartupPath + "\\sound\\";
        //今日寿星
        List<ContactsInfo> todayBirthday = new List<ContactsInfo>();
        //最近寿星
        List<ContactsInfo> recentlyBirthday = new List<ContactsInfo>();
        public frmMain()
        {
            InitializeComponent();
        }
        //初始化相册信息
        private void InitImglist()
        {
            string imgpath = Application.StartupPath + "\\face";
            //检查程序目录中是否有face目录
            if (Directory.Exists(imgpath) == false)
            {
                //创建目录
                Directory.CreateDirectory(imgpath);
                //把资源图片保存到指定目录
                Assembly assem = Assembly.GetExecutingAssembly();
                Stream stream = assem.GetManifestResourceStream("Remind.View.Resources.1.jpg");
                Stream stream1 = assem.GetManifestResourceStream("Remind.View.Resources.2.jpg");
                Image img = Image.FromStream(stream);
                Image img1 = Image.FromStream(stream1);
                img.Save(imgpath + "\\1.jpg");
                img1.Save(imgpath + "\\2.jpg");
                img.Dispose();
                img1.Dispose();
            }
            //读取face目录下的图片加入到相册中
            faceImageList.Images.Clear();
            foreach (string targetDir in Directory.GetFiles(imgpath))
            {
                Image img = Image.FromFile(targetDir);
                faceImageList.Images.Add(img);
            }
        }

        //加载分组
        private void AddGroup()
        {
            //读取所有分组信息
            IList<GroupInfo> groups = gBLL.GetGroup();
            int i = 0;
            sideBar.Groups.Clear();
            todayBirthday.Clear();
            foreach (GroupInfo item in groups)
            {
                IList<ContactsInfo> contacts = cBLL.GetContactsByGid(item.Gid);//获取该组联系人
                this.sideBar.AddGroup(item.Gname + "[" + contacts.Count + "]");//填加组名称
                foreach (ContactsInfo contact in contacts)
                {
                    SbItem sbItem = new SbItem();
                    sbItem.Text = contact.Cname;
                    sbItem.Tag = contact.Cid;
                    int monthResult = contact.Cbirthday.Month.CompareTo(DateTime.Now.Month);//比较月份检查
                    int dayResult = contact.Cbirthday.Day.CompareTo(DateTime.Now.Day);//比较当日

                    //当日寿星
                    if (monthResult == 0 && dayResult == 0)
                        todayBirthday.Add(contact);
                    //如果相册里面的表情数少于保存的数量
                    sbItem.ImageIndex = contact.Cface >= faceImageList.Images.Count ? 0 : contact.Cface;
                    this.sideBar.Groups[i].Items.Add(sbItem);
                }
                i++;
            }
            if (todayBirthday.Count > 0)
            {
                SoundPlayer aa = new SoundPlayer(soundpath + "Global.wav");
                aa.Play();
            }
        }

        //初始化
        private void frmMain_Load(object sender, EventArgs e)
        {
            InitImglist();
            AddGroup();
            try
            {
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            toolStripStatusLabel1.Text = "今天是：" + DateTime.Now.ToString("yyyy-M-d");
        }
        //sidebar右键菜单
        private void contextMenuStripView_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Text == "列表")
                sideBar.View = SbView.List;
            else if (e.ClickedItem.Text == "小图标")
                sideBar.View = SbView.SmallIcon;
            else if (e.ClickedItem.Text == "大图标")
                sideBar.View = SbView.LargeIcon;
            else if (e.ClickedItem.Text == "添加分组")
            {
                frmAddGroup addGroup = new frmAddGroup(this.sideBar);
                try
                {
                    addGroup.ShowDialog(this);
                }
                finally
                {
                    addGroup.Dispose();
                }
            }
            else if (e.ClickedItem.Text == "重命名")
            {
                GroupInfo groupInfo = gBLL.GetGroupByGname(sideBar.VisibleGroup.Text.Substring(0, sideBar.VisibleGroup.Text.IndexOf("[")));
                frmAddGroup addGroup = new frmAddGroup(sideBar, groupInfo);
                try
                {
                    addGroup.ShowDialog(this);
                }
                finally
                {
                    addGroup.Dispose();
                }
            }
            else if (e.ClickedItem.Text == "删除组")
            {
                if (MessageBox.Show("确定删除" + sideBar.VisibleGroup.Text.Substring(0, sideBar.VisibleGroup.Text.IndexOf("[")) + "组吗？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (gBLL.DelGroup(gBLL.GetGroupByGname(sideBar.VisibleGroup.Text.Substring(0, sideBar.VisibleGroup.Text.IndexOf("[")))) > 0)
                        sideBar.Groups.RemoveAt(sideBar.VisibleGroupIndex);
                }
            }
            else if (e.ClickedItem.Text == "详细信息")
            {
                ShowContactsInfo(sideBar);
            }
            else if (e.ClickedItem.Text == "添加联系人")
            {
                FrmAddContact frmAddContact = new FrmAddContact(faceImageList);
                try
                {
                    frmAddContact.ShowDialog(this);
                }
                finally
                {
                    frmAddContact.Dispose();
                    AddGroup();
                }
            }
            else if (e.ClickedItem.Text == "删除联系人")
            {
                ContactsInfo contact = cBLL.GetContactByCid((int)sideBar.SeletedItem.Tag);
                if (MessageBox.Show("您确定删除" + contact.Cname + "的电话、地址,网络信息吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    cBLL.DelContact(contact);
                    AddGroup();
                }
            }
        }
        //显示详细信息
        private void ShowContactsInfo(SideBar side)
        {
            ContactsInfo contact = cBLL.GetContactByCid((int)side.SeletedItem.Tag);
            int index = contact.Cface >= faceImageList.Images.Count ? 0 : contact.Cface;
            Image img = faceImageList.Images[index];
            //把头像组传递到编辑窗体
            frmContact contactFrm = new frmContact(side, faceImageList);
            try
            {
                contactFrm.ShowDialog(this);
            }
            finally
            {
                contactFrm.Dispose();
                AddGroup();
            }
        }

        private void sideBar_ItemClick(SbItemEventArgs e)
        {
            ShowContactsInfo(sideBar);
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }

        private void frmMain_MinimumSizeChanged(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Show();//显示主窗体
                this.WindowState = FormWindowState.Normal;//显示
                this.Activate();//激活窗体
            }
        }

        private void notifycontextMenuStript_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Text == "退出提醒")
            {
                if (MessageBox.Show("你确定要退出程序吗？", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    this.notifyIcon.Visible = false;
                    this.Close();
                    this.Dispose();
                    Application.Exit();
                }
            }
            if (e.ClickedItem.Text == "打开提醒")
            {
                this.Show();//显示主窗体
                this.WindowState = FormWindowState.Normal;//显示
                this.Activate();//激活窗体
            }
        }

        private void sysToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Name == "optiontoolStripMenuItem")
            {
                FrmOption frm = new FrmOption();
                try
                {
                    frm.ShowDialog();
                }
                finally
                {
                    frm.Dispose();
                }
            }
            else if (e.ClickedItem.Name == "exmitToolStripMenuItem")
            {
                //if (MessageBox.Show("你确定要退出程序吗？", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                //{
                //    this.notifyIcon.Visible = false;
                //    this.Close();
                //    Application.Exit();
                //}
                this.notifyIcon.Visible = false;
                this.Close();
                Application.Exit();
            }
        }

        private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl.SelectedIndex == 1)
            {
                //判断联系人中是否有今天过生日的人
                if (todayBirthday.Count > 0)
                {
                    //清除面板上的信息
                    this.todayBirthdaytabPage.Controls.Clear();
                    //把side添加到面板中
                    this.todayBirthdaytabPage.Controls.Add(this.todayBirthdaymySideBar);
                    //设置todayBirthdaymySideBar的属性
                    todayBirthdaymySideBar.ImageList = faceImageList;
                    //清除sidebar中的分组和组成员
                    this.todayBirthdaymySideBar.Groups.Clear();
                    //设置寿星成员
                    this.todayBirthdaymySideBar.AddGroup("今日寿星");
                    foreach (ContactsInfo item in todayBirthday)
                    {
                        SbItem sbItem = new SbItem();
                        sbItem.Text = item.Cname;
                        sbItem.Tag = item.Cid;
                        sbItem.ImageIndex = item.Cface;
                        this.todayBirthdaymySideBar.Groups[0].Items.Add(sbItem);
                    }
                }
                else
                {
                    //清除面板上的信息
                    this.todayBirthdaytabPage.Controls.Clear();
                    //把side添加到面板中
                    this.todayBirthdaytabPage.Controls.Add(this.lblMessageInfo);
                    //显示错误信息
                    this.lblMessageInfo.Text = "今天没有过生日的联系人！";
                }
            }
            if (tabControl.SelectedIndex == 2)
            {
                //初始化选择框
                this.recentlycomboBox.SelectedIndex = 0;
                RecentlyCheck(7);
            }
        }

        //查询最近过生日的朋友
        private void RecentlyCheck(int day)
        {
            //默认查询最近7天过生日的朋友
            IList<ContactsInfo> allContacts = cBLL.GetAllContacts();
            IList<ContactsInfo> recentlyContacts = new List<ContactsInfo>();
            if (allContacts != null)
            {
                foreach (ContactsInfo item in allContacts)
                {
                    //把出生日期转换成当前年
                    int age = DateTime.Now.Year - item.Cbirthday.Year;
                    DateTime nowBirthday = item.Cbirthday.AddYears(age);
                    //
                    int temp = nowBirthday.DayOfYear - DateTime.Now.DayOfYear;
                    if (temp <= day && temp >= 0)
                        recentlyContacts.Add(item);
                }
            }
            if (recentlyContacts.Count > 0)
            {
                //清除sidebar中的分组和组成员
                this.recentlymySideBar.Groups.Clear();
                //设置寿星成员
                this.recentlymySideBar.AddGroup("最近" + day + "天寿星");
                foreach (ContactsInfo item in recentlyContacts)
                {
                    SbItem sbItem = new SbItem();
                    sbItem.Text = item.Cname;
                    sbItem.Text = item.Cname;
                    sbItem.Tag = item.Cid;
                    sbItem.ImageIndex = item.Cface >= faceImageList.Images.Count ? 0 : item.Cface;
                    this.recentlymySideBar.Groups[0].Items.Add(sbItem);
                }
                if (this.recentlytabPage.Controls.Find("recentlymySideBar", false).Count() <= 0)
                {
                    this.recentlytabPage.Controls.Remove(this.lblMessageInfo);
                    this.recentlytabPage.Controls.Add(this.recentlymySideBar);
                }
            }
            else
            {
                //清除面板上的sidebar
                this.recentlytabPage.Controls.Remove(this.recentlymySideBar);
                //加上错误信息
                this.recentlytabPage.Controls.Add(this.lblMessageInfo);
                //显示错误信息
                this.lblMessageInfo.Text = "最近" + day + "天没有过生日的联系人！";
            }
        }
        //查询历史数据
        private void btnSearch_Click(object sender, EventArgs e)
        {
            int day = 7;
            //判断输入类型
            try
            {
                day = Convert.ToInt32(this.recentlycomboBox.Text);

            }
            catch (FormatException)
            {
                //清除面板上的sidebar
                this.recentlytabPage.Controls.Remove(this.recentlymySideBar);
                //加上错误信息
                this.recentlytabPage.Controls.Add(this.lblMessageInfo);
                //显示错误信息
                this.lblMessageInfo.Text = "请输入1-31之间的数字。";
            }
            if (day > 31 || day <= 0)
            {
                //清除面板上的sidebar
                this.recentlytabPage.Controls.Remove(this.recentlymySideBar);
                //加上错误信息
                this.recentlytabPage.Controls.Add(this.lblMessageInfo);
                //显示错误信息
                this.lblMessageInfo.Text = "请输入1-31之间的数字。";
            }
            else
            {
                RecentlyCheck(day);
            }
        }

        private void contextMenuStripView_Opening(object sender, CancelEventArgs e)
        {
            ShowSbSelectedItem(sideBar.SeletedItem == null);
        }
        //控制是否显示
        private void ShowSbSelectedItem(bool isShow)
        {
            if (sideBar.VisibleGroup == null)
            {
                addGrouptoolStripMenuItem.Visible = true;
                deltoolStripMenuItem.Visible = false;
                listToolStripMenuItem.Visible = false;
                largeiconToolStripMenuItem.Visible = false;
                smallicontoolStripMenuItem.Visible = false;
                renametoolStripMenuItem.Visible = false;
                toolStripSeparator1.Visible = false;
                basictoolStripMenuItem.Visible = false;
                delcontactoolStripMenuItem.Visible = false;
                addcontactStripMenuItem.Visible = false;
                addcontactStripMenuItem.Visible = false;
            }
            else
            {
                addGrouptoolStripMenuItem.Visible = isShow;
                listToolStripMenuItem.Visible = isShow;
                largeiconToolStripMenuItem.Visible = isShow;
                smallicontoolStripMenuItem.Visible = isShow;
                renametoolStripMenuItem.Visible = isShow;
                toolStripSeparator1.Visible = isShow;
                basictoolStripMenuItem.Visible = !isShow;
                delcontactoolStripMenuItem.Visible = !isShow;
                addcontactStripMenuItem.Visible = !isShow;
                deltoolStripMenuItem.Visible = (sideBar.VisibleGroup.Items.Count == 0);
            }

        }
        //
        private void todayBirthdaymySideBar_ItemDoubleClick(SbItemEventArgs e)
        {
            ShowContactsInfo(todayBirthdaymySideBar);
        }
        //
        private void recentlymySideBar_ItemDoubleClick(SbItemEventArgs e)
        {
            ShowContactsInfo(recentlymySideBar);
        }

        private void SearchtoolStripButton_Click(object sender, EventArgs e)
        {
            //按照姓名模糊搜索
            if (!string.IsNullOrEmpty(searchtoolStripTextBox.Text.Trim()))
            {
                string strSearch = searchtoolStripTextBox.Text;
                IList<ContactsInfo> searchContacts = cBLL.SearchByCName(strSearch);
                if (searchContacts.Count > 0)
                {
                    sideBar.Groups.Clear();
                    //在sidebar新增一组
                    SbGroup sg = new SbGroup("查询结果");
                    foreach (ContactsInfo item in searchContacts)
                    {
                        SbItem sb = new SbItem(item.Cname, (item.Cface >= faceImageList.Images.Count) ? 0 : item.Cface);
                        sb.Tag = item.Cid;
                        sg.Items.Add(sb);
                    }
                    sideBar.AddGroup(sg);
                }
            }
            else
            {
                AddGroup();
            }

        }

        private void sideBar_VisibleGroupChanged(SbGroupEventArgs e)
        {
            SoundPlayer aa = new SoundPlayer(soundpath + "folder.wav");
            aa.Play();
        }

        private void showToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void contactsToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if(e.ClickedItem.Text=="添加分组")
            {
                frmAddGroup addGroup = new frmAddGroup(this.sideBar);
                try
                {
                    addGroup.ShowDialog(this);
                }
                finally
                {
                    addGroup.Dispose();
                }
            }
            else if (e.ClickedItem.Text == "添加联系人")
            {
                if (sideBar.VisibleGroup == null)
                {
                    MessageBox.Show("请先添加联系人分组,然后添加联系人.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    FrmAddContact frmAddContact = new FrmAddContact(faceImageList);
                    try
                    {
                        frmAddContact.ShowDialog(this);
                    }
                    finally
                    {
                        frmAddContact.Dispose();
                        AddGroup();
                    }
                }
            }
            else if (e.ClickedItem.Text == "导入联系人")
            {
                FrmImport frmImport = new FrmImport();
                try
                {
                    frmImport.ShowDialog(this);
                }
                finally
                {
                    frmImport.Dispose();
                    AddGroup();
                }
            }
            else if (e.ClickedItem.Text == "报表输出")
            {
                FrmReport frmReport = new FrmReport();
                frmReport.ShowDialog();
            }
            else if (e.ClickedItem.Text.ToLower() == "批量删除")
            {
                FrmReports frm = new FrmReports();
                try
                {
                    frm.ShowDialog(this);
                }
                finally
                {
                    frm.Dispose();
                    AddGroup();
                }
            }
        }
    }
}
